package com.qf.cx.simplenms.webservice.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qf.cx.simplenms.persist.entity.ReaderGroupEntity;
import com.qf.cx.simplenms.persist.service.api.ReaderGroupService;
import com.qf.cx.simplenms.webservice.model.ReaderGroup;

@RestController
@RequestMapping(path = "/readergroups")
public class ReaderGroupController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ReaderGroupService readerGroupService;

	@RequestMapping(method = RequestMethod.GET)
	public List<ReaderGroup> getReaderGroups() {
		List<ReaderGroupEntity> readerGroups = readerGroupService.getReaderGroups();
		List<ReaderGroup> list = new ArrayList<>();
		readerGroups.forEach(t -> list.add(ReaderGroup.from(t)));
		return list;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void addReaderGroups(@RequestBody List<ReaderGroup> readerGroups) {
		logger.debug("add reader groups {}", readerGroups);
		List<ReaderGroupEntity> readerGroupEntities = new ArrayList<>(readerGroups.size());
		readerGroups.forEach(t -> readerGroupEntities.add(t.toReaderGroupEntity()));
		readerGroupService.addReaderGroups(readerGroupEntities);
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.PUT)
	public void updateReaderGroup(@PathVariable("name") String name,
	        @RequestBody ReaderGroup readerGroup) {
		logger.debug("update reader group {}", readerGroup);
		ReaderGroupEntity readerGroupEntity = readerGroup.toReaderGroupEntity();
		readerGroupService.updateReaderGroup(readerGroupEntity);
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.DELETE)
	public void deleteReaderGroup(@PathVariable("name") String name) {
		logger.debug("delete reader group {}", name);
		readerGroupService.deleteReaderGroup(name);
	}

}